@namespace BulmaRazor.Components
@using System.ComponentModel
@inherits BulmaComponentBase
@inject BulmaRazorJsInterop JsInterop
@inject NavigationManager nm

<a id="@Id" @attributes="Attributes" class="@classes" @onclick="e => HandleClick()">
    @ChildContent

    @if (ItemParent.SubList != null)
    {
        if (IsClose)
        {
            <Icon IconClass="fa fa-angle-right" class="@B.PulledRight"></Icon>
        }
        else
        {
            <Icon IconClass="fa fa-angle-down" class="@B.PulledRight"></Icon>
        }
    }
</a>

@code{

    private readonly string Id = "menulink" + Guid.NewGuid().ToString("N");

    string classes => CssBuilder.Default("")
        .AddClassFromAttributes(Attributes)
        .AddClass("is-active", IsActive)
        .Build();

    internal string Href { get; set; }

    [Parameter]
    public bool IsActive { get; set; }

    [Parameter]
    public bool IsClose { get; set; }


    [CascadingParameter]
    public Menu MenuParent { get; set; }

    [CascadingParameter]
    public MenuItem ItemParent { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }


    internal void Active(bool isActive)
    {
        if (isActive != IsActive)
        {
            IsActive = isActive;
            StateHasChanged();
        }
    }

    private async Task HandleClick()
    {
        if (ItemParent?.SubList != null)
        {
            if (IsClose)
            {
                await JsInterop.SlideDown(ItemParent.SubList.Id, "fast");
                IsClose = false;
            }
            else
            {
                await JsInterop.SlideUp(ItemParent.SubList.Id, "fast");
                IsClose = true;
            }
        }
        else
        {
            await MenuParent?.ClickItem(ItemParent);
        }
    }


    protected override void OnInitialized()
    {
        if (ItemParent != null)
        {
            ItemParent.Title = this;
        }
        base.OnInitialized();
    }

    public override async Task SetParametersAsync(ParameterView parameters)
    {
        await base.SetParametersAsync(parameters);
        if (Attributes.TryGetValue("href", out object value))
        {
            Href = value.ToString();
        }
    }

}